<template>
  <div class="form-container">
    <el-form v-if="state.showLogin" ref="loginFormRef" :model="state.loginForm" status-icon :hide-required-asterisk="true" :rules="rules" label-width="100px" class="login-form">
      <el-form-item label="账号" prop="username">
        <el-input v-model="state.loginForm.username" autocomplete="off" placeholder="请输入登录账号(super)"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="state.loginForm.password" type="password" autocomplete="off" placeholder="请输入密码(super)"></el-input>
      </el-form-item>

      <el-form-item>
        <div class="btn-container">
          <el-button type="primary" style="width: 100%" @click="submitForm()">登录</el-button>
        </div>
        <div class="operation">
          <span class="free-register" @click="state.showLogin = !state.showLogin">免费注册</span>
          <span class="forget-password" @click="handleForget">忘记密码</span>
        </div>
      </el-form-item>
    </el-form>
    <el-form v-if="!state.showLogin" ref="registerRef" :model="state.registerForm" status-icon :hide-required-asterisk="true" :rules="rules" label-width="100px" class="login-form">
      <el-form-item label="账号" prop="username">
        <el-input v-model="state.registerForm.username" autocomplete="off" placeholder="请输入账号">
          
        </el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="state.registerForm.email" autocomplete="off" placeholder="请输入注册邮箱">
          <template #append>
            <el-button :disabled="sendingCode" @click="handleGetCaptcha">{{ codeText }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="capcha">
        <el-input v-model.number="state.registerForm.capcha" maxlength="10" autocomplete="off" placeholder="请输入验证码"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="state.registerForm.password" type="password" autocomplete="off" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input v-model="state.registerForm.checkPass" type="password" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item>
        <div class="btn-container">
          <el-button type="primary" style="width: 100%" @click="handleRegister()">完成注册</el-button>
        </div>
        <div class="go-login">
          <span class="to-login" @click="state.showLogin = !state.showLogin">已有账号<em>去登陆</em></span>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { defineComponent, ref, toRefs, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { encrypt } from '@/utils/aes' // aes 密码加密
import { useStore } from '@/store'
// import Service from '../api/index'
import Service from '@/api/Service'
import LoginApi from '@/api/system/LoginApi'
import ApiInfo from '@/api/index'
import EnvermentConfig from '../../../../public/config'

type VoidNoop = (arg0?: Error) => void
const router = useRouter()
const route = useRoute()
const loginFormRef = ref()
const registerRef = ref()
const store = useStore()
const sendingCode = ref(false)
const codeText = ref('获取验证码')

// 定义数据
interface stateType {
  loginForm: {
    username: string
    password: string,
    grant_type: string,
    scope: string
  }
  registerForm: {
    username: string
    email: string
    capcha: number | null
    password: string
    checkPass: string
  }
  showLogin: boolean
}

    const state = reactive<stateType>({
      loginForm: {
        username: 'super',
        password: 'super',
        grant_type: EnvermentConfig.grantType,
        scope: EnvermentConfig.scope
      },
      registerForm: {
        username: '',
        email: '',
        capcha: null,
        password: '',
        checkPass: ''
      },
      showLogin: true
    })

    // eslint-disable-next-line no-unused-vars
    const validatePass2 = (rule: any, value: string, callback: VoidNoop) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== state.registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const validatePass = (rule: any, value: string, callback: VoidNoop) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (state.registerForm.checkPass !== '') {
          registerRef.value.validateField('checkPass')
        }
        callback()
      }
    }
    const rules = {
      password: [
        { validator: validatePass, trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
      ],
      checkPass: [{ validator: validatePass2, trigger: 'blur' }],
      username: [
        { required: true, message: '请输正确账号', trigger: 'change' },
      ],
      email: [
        { required: true, message: '请输入注册邮箱', trigger: 'change' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
      ],
      capcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
    }

    // methods

    /**
     * @description  用户登录接口
     *
     */
    const submitForm = () => {
      loginFormRef.value.validate(async (valid: any) => {
        if (valid) {
          try {
            const { username, password,grant_type,scope } = state.loginForm
            const data = {
              grant_type,
              scope,
              username,
              password
              // password: encrypt(password)
            }
            sessionStorage.clear()
            // 登录
            const apinfo = ApiInfo.getApiInfoAndData(LoginApi.userLogin,data);
            const res = await Service.postForm(apinfo);
          
            const accessToken = res?.access_token ?? null  
            
            // 缓存token, 获取用户信息
            if (accessToken) {
              sessionStorage.setItem('auth', 'true')
              sessionStorage.setItem('accessToken', accessToken)

              // 根据账号获取用户信息
              const apinfo = ApiInfo.getApiInfoAndData(LoginApi.userInfo, { username });
              const resp = await Service.get(apinfo)
              
              // 将角色存储到全局vuex roles
              if (resp.code === 200) {
                store.dispatch('permissionModule/getPermissonRoles', resp.respData)
                store.dispatch('permissionModule/getPermissonRoutes', resp.respData)
              }
              // // 先进行异步路由处理
              // store.dispatch('permissionModule/getPermissions')
              
              if (route.query.redirect) {
                const path = route.query.redirect
                router.push({ path: path as string })
              } else {
                router.push('/')
              }
            
            } else {
              ElMessage({
                type: 'warning',
                message: '账号或者密码有误'
              })
            }
          } catch (err) {
            // ElMessage({
            //   type: 'error',
            //   message: err.msg
            // })
          }
        }
        return false
      })
    }
    /**
     * @description 处理注册接口
     */
    const handleRegister = () => {
      registerRef.value.validate(async (valid: any) => {
        if (valid) {
          try {
            const { username,email, password, capcha } = state.registerForm
            const data = {
              userName: username,
              email,
              capcha,
              password
              // password: encrypt(password)
            }
            // 注册
            const registerInfo = ApiInfo.getApiInfoAndData(LoginApi.userRegister,data);

            Service.post(registerInfo)
              .then((res: any) => {
                if (res.code === 200) {
                  ElMessage({
                    type: 'success',
                    message: '注册成功'
                  })
                  state.showLogin = true
                } else {
                  ElMessage({
                    type: 'warning',
                    message: res.respData.msg
                  })
                }
              })
              .catch((err) => {
                ElMessage({
                  type: 'warning',
                  message: err.message
                })
              })
          } catch (err) {
            ElMessage({
              type: 'error',
              message: err.message
            })
          }
        }
      })
    }
    /**
     * @description 获取验证码状态
     */
    const getCodeSucces = () => {
      let countDown = 60
      sendingCode.value = true
      const interval = setInterval(() => {
        if (countDown > 0) {
          codeText.value = `已发送(${countDown}s)`
          countDown -= 1
        } else {
          clearInterval(interval)
          sendingCode.value = false
          codeText.value = '获取验证码'
        }
      }, 1000)
    }
    /**
     * @description 获取验证码
     */
    const handleGetCaptcha = async (): Promise<boolean> => {
      try {
        const { email } = state.registerForm
        if (!email) {
          ElMessage({
            type: 'warning',
            message: '请输入注册邮箱'
          })
          return false
        }
        const data = {
          email
        }
        // 获取验证码
        const apiInfo = ApiInfo.getApiInfoAndData(LoginApi.sendCaptcha,data);
        const res = await Service.request(apiInfo)
        if (res.status === 0) {
          ElMessage({
            type: 'success',
            message: res.message
          })
          getCodeSucces()
          return true
        }
        ElMessage({
          type: 'warning',
          message: res.message
        })
        return false
      } catch (err) {
        console.error(err)
        return false
      }
    }
    /**
     * @description 忘记密码
     */
    const handleForget = () => {
      emit('toResetPwd')
    }


// eslint-disable-next-line no-unused-vars
// type VoidNoop = (arg0?: Error) => void
// export default defineComponent({
//   name: 'LoginForm',
//   emits: ['toResetPwd'],
//   setup(_props, { emit }) {
    
//     return {
//       ...toRefs(state),
//       loginFormRef,
//       registerRef,
//       sendingCode,
//       codeText,
//       rules,
//       submitForm,
//       handleRegister,
//       handleGetCaptcha,
//       handleForget
//     }
//   }
// })
</script>
<style lang="stylus" scoped>
.form-container{
  width:100%;

  :deep(.el-input-group__append) {
    padding:0px 7px;
  }

  :deep(.el-input-group__prepend) {
    padding:0px 7px;
  }

  .login-form{
    width:100%;
    margin: 0 auto;
  }
  .go-login{
    font-size: 12px;
    cursor: pointer;
    display:flex;
    flex-direction:row ;
    justify-content: center;
    align-items :center;

    .to-login{
      color: #9fa2a8;

      em{
        color: #2878ff;
      }
    }
  }

  .operation{
    font-size: 12px;
    cursor: pointer;
    display:flex;
    flex-direction:row ;
    justify-content: space-between;
    align-items :center;

    .free-register{
        color: #2878ff;
      }

      .forget-password{
        color: #9fa2a8;
      }
    }
    .btn-container{
        width:100%;
        display :flex;
        flex-direction:row;
        justify-content :flex-start;
        align-items :center;
    }
  }
</style>
